// store/task.js - 任务状态管理
import { defineStore } from 'pinia';
import { taskApi } from '../api/task.js';
import { getTaskStatus, setTaskStatus } from '../utils/storage.js';

export const useTaskStore = defineStore('task', {
  state: () => ({
    // 任务列表
    taskList: [],
    // 用户任务列表
    userTaskList: [],
    // 任务详情
    currentTask: null,
    // 任务状态映射
    taskStatusMap: {},
    // 分页信息
    pagination: {
      currentPage: 1,
      pageSize: 10,
      total: 0,
      hasMore: true
    },
    // 加载状态
    loading: false,
    // 详情加载状态
    detailLoading: false,
    // 错误信息
    error: null,
    // 搜索关键词
    searchKeyword: '',
    // 筛选条件
    filters: {
      status: '', // all, pending, completed, expired
      category: '',
      sort: 'default' // default, newest, highest_points
    }
  }),

  getters: {
    // 获取任务数量
    taskCount: (state) => state.taskList.length,
    // 获取用户任务数量
    userTaskCount: (state) => state.userTaskList.length,
    // 获取进行中的任务
    ongoingTasks: (state) => {
      return state.userTaskList.filter(task => task.status === 'ongoing' || task.status === 'pending_review');
    },
    // 获取已完成的任务
    completedTasks: (state) => {
      return state.userTaskList.filter(task => task.status === 'completed');
    },
    // 获取待领取的任务
    pendingTasks: (state) => {
      return state.taskList.filter(task => task.status === 'pending');
    },
    // 根据ID获取任务
    getTaskById: (state) => (id) => {
      return state.taskList.find(task => task.id === id) || state.userTaskList.find(task => task.id === id) || null;
    },
    // 获取任务状态
    getTaskStatus: (state) => (taskId) => {
      return state.taskStatusMap[taskId] || getTaskStatus(taskId) || null;
    },
    // 搜索后的任务列表
    searchedTasks: (state) => {
      if (!state.searchKeyword) return state.taskList;
      
      const keyword = state.searchKeyword.toLowerCase();
      return state.taskList.filter(task => 
        task.title.toLowerCase().includes(keyword) || 
        task.description.toLowerCase().includes(keyword)
      );
    },
    // 筛选后的任务列表
    filteredTasks: (state) => {
      let tasks = state.searchedTasks;
      
      // 按状态筛选
      if (state.filters.status && state.filters.status !== 'all') {
        tasks = tasks.filter(task => task.status === state.filters.status);
      }
      
      // 按分类筛选
      if (state.filters.category) {
        tasks = tasks.filter(task => task.category === state.filters.category);
      }
      
      // 排序
      switch (state.filters.sort) {
        case 'newest':
          tasks.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
          break;
        case 'highest_points':
          tasks.sort((a, b) => b.points - a.points);
          break;
        default:
          // 默认排序
          break;
      }
      
      return tasks;
    }
  },

  actions: {
    // 设置任务列表
    setTaskList(tasks) {
      this.taskList = tasks;
    },

    // 设置用户任务列表
    setUserTaskList(tasks) {
      this.userTaskList = tasks;
    },

    // 设置当前任务
    setCurrentTask(task) {
      this.currentTask = task;
    },

    // 设置任务状态
    setTaskStatus(taskId, status) {
      this.taskStatusMap[taskId] = status;
      setTaskStatus(taskId, status);
      
      // 更新列表中的任务状态
      const taskIndex = this.taskList.findIndex(t => t.id === taskId);
      if (taskIndex !== -1) {
        this.taskList[taskIndex].status = status;
      }
      
      const userTaskIndex = this.userTaskList.findIndex(t => t.id === taskId);
      if (userTaskIndex !== -1) {
        this.userTaskList[userTaskIndex].status = status;
      }
      
      // 更新当前任务状态
      if (this.currentTask && this.currentTask.id === taskId) {
        this.currentTask.status = status;
      }
    },

    // 设置分页信息
    setPagination(pagination) {
      this.pagination = { ...this.pagination, ...pagination };
    },

    // 设置搜索关键词
    setSearchKeyword(keyword) {
      this.searchKeyword = keyword;
    },

    // 设置筛选条件
    setFilters(filters) {
      this.filters = { ...this.filters, ...filters };
    },

    // 重置筛选条件
    resetFilters() {
      this.filters = {
        status: '',
        category: '',
        sort: 'default'
      };
      this.searchKeyword = '';
    },

    // 获取任务列表
    async fetchTaskList(params = {}, append = false) {
      try {
        this.loading = true;
        this.error = null;
        
        const result = await taskApi.getTaskList(params);
        
        if (result.code === 1) {
          const tasks = result.data?.list || [];
          
          if (append) {
            // 追加模式（加载更多）
            this.taskList = [...this.taskList, ...tasks];
          } else {
            // 替换模式（刷新）
            this.taskList = tasks;
          }
          
          // 更新分页信息
          this.setPagination({
            currentPage: params.page || 1,
            pageSize: params.limit || 10,
            total: result.data?.total || 0,
            hasMore: this.taskList.length < (result.data?.total || 0)
          });
          
          return true;
        } else {
          this.error = result.msg || '获取任务列表失败';
          return false;
        }
      } catch (error) {
        console.error('获取任务列表失败:', error);
        this.error = '获取任务列表失败，请稍后重试';
        return false;
      } finally {
        this.loading = false;
      }
    },

    // 获取用户任务列表
    async fetchUserTaskList(params = {}, append = false) {
      try {
        this.loading = true;
        this.error = null;
        
        const result = await taskApi.getUserTaskList(params);
        
        if (result.code === 1) {
          const tasks = result.data?.list || [];
          
          if (append) {
            this.userTaskList = [...this.userTaskList, ...tasks];
          } else {
            this.userTaskList = tasks;
          }
          
          // 更新分页信息
          this.setPagination({
            currentPage: params.page || 1,
            pageSize: params.limit || 10,
            total: result.data?.total || 0,
            hasMore: this.userTaskList.length < (result.data?.total || 0)
          });
          
          // 更新任务状态映射
          tasks.forEach(task => {
            this.setTaskStatus(task.id, task.status);
          });
          
          return true;
        } else {
          this.error = result.msg || '获取用户任务列表失败';
          return false;
        }
      } catch (error) {
        console.error('获取用户任务列表失败:', error);
        this.error = '获取用户任务列表失败，请稍后重试';
        return false;
      } finally {
        this.loading = false;
      }
    },

    // 获取任务详情
    async fetchTaskDetail(taskId) {
      try {
        this.detailLoading = true;
        this.error = null;
        const result = await taskApi.getTaskDetail(taskId);
        
        if (result.code === 1) {
          this.setCurrentTask(result.data?.task || null);
          return true;
        } else {
          this.error = result.msg || '获取任务详情失败';
          return false;
        }
      } catch (error) {
        console.error('获取任务详情失败:', error);
        this.error = '获取任务详情失败，请稍后重试';
        return false;
      } finally {
        this.detailLoading = false;
      }
    },

    // 领取任务
    async acceptTask(taskId) {
      try {
        this.loading = true;
        this.error = null;
        
        const result = await taskApi.acceptTask(taskId);
        
        if (result.code === 1) {
          // 更新任务状态
          this.setTaskStatus(taskId, 'ongoing');
          return { success: true, ...result };
        } else {
          return { success: false, message: result.msg || '领取任务失败' };
        }
      } catch (error) {
        console.error('领取任务失败:', error);
        return { success: false, message: '领取任务失败，请稍后重试' };
      } finally {
        this.loading = false;
      }
    },

    // 提交任务
    async submitTask(taskId, data) {
      try {
        this.loading = true;
        this.error = null;
        
        const result = await taskApi.submitTask(taskId, data);
        
        if (result.code === 1) {
          // 更新任务状态
          this.setTaskStatus(taskId, 'pending_review');
          return { success: true, ...result };
        } else {
          return { success: false, message: result.msg || '提交任务失败' };
        }
      } catch (error) {
        console.error('提交任务失败:', error);
        return { success: false, message: '提交任务失败，请稍后重试' };
      } finally {
        this.loading = false;
      }
    },

    // 取消任务
    async cancelTask(taskId) {
      try {
        this.loading = true;
        this.error = null;
        
        const result = await taskApi.cancelTask(taskId);
        
        if (result.code === 1) {
          // 更新任务状态
          this.setTaskStatus(taskId, 'canceled');
          return { success: true, ...result };
        } else {
          return { success: false, message: result.msg || '取消任务失败' };
        }
      } catch (error) {
        console.error('取消任务失败:', error);
        return { success: false, message: '取消任务失败，请稍后重试' };
      } finally {
        this.loading = false;
      }
    },

    // 加载更多任务
    async loadMoreTasks() {
      if (!this.pagination.hasMore || this.loading) return false;
      
      const nextPage = this.pagination.currentPage + 1;
      return await this.fetchTaskList({
        ...this.filters,
        page: nextPage,
        limit: this.pagination.pageSize
      }, true);
    },

    // 刷新任务列表
    async refreshTaskList() {
      return await this.fetchTaskList({
        ...this.filters,
        page: 1,
        limit: this.pagination.pageSize
      });
    },

    // 重置状态
    resetState() {
      this.taskList = [];
      this.userTaskList = [];
      this.currentTask = null;
      this.taskStatusMap = {};
      this.pagination = {
        currentPage: 1,
        pageSize: 10,
        total: 0,
        hasMore: true
      };
      this.loading = false;
      this.detailLoading = false;
      this.error = null;
      this.searchKeyword = '';
      this.resetFilters();
    }
  }
});